package ${domain}.module.wsys.mgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.auth.Token;
import ${domain}.frame.utils.IDgenerator;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.Message;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.Dict;
import ${domain}.module.wsys.mpr.DictMapper;
import ${domain}.module.wsys.req.DictCreateRequest;
import ${domain}.module.wsys.req.DictDeleteRequest;
import ${domain}.module.wsys.req.DictFindRequest;
import ${domain}.module.wsys.req.DictItemFindRequest;
import ${domain}.module.wsys.req.DictLoadRequest;
import ${domain}.module.wsys.req.DictUpdateRequest;
import ${domain}.module.wsys.rsp.DictCreateResponse;
import ${domain}.module.wsys.rsp.DictDeleteResponse;
import ${domain}.module.wsys.rsp.DictFindResponse;
import ${domain}.module.wsys.rsp.DictItemFindResponse;
import ${domain}.module.wsys.rsp.DictLoadResponse;
import ${domain}.module.wsys.rsp.DictUpdateResponse;

import java.util.List;

/**
 * DICT - 字典
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
@Transactional
@Service
public class DictManagerImpl implements DictManager {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private DictItemManager dictItemManager;

    /**
     * 插入
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public DictCreateResponse create(DictCreateRequest request, Token token) {
        DictCreateResponse response = new DictCreateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        {// 检查字典名称是否重复
            DictFindRequest dictFindRequest = new DictFindRequest();
            dictFindRequest.setDictName(request.getDictName());
            DictFindResponse dictFindResponse = this.find(dictFindRequest, token);
            if (dictFindResponse.hasError()) {
                response.addErrors(dictFindResponse.getErrors());
                return response;
            } else if (dictFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.BUSINESS_ERROR, "[" + request.getDictName() + "]字典名称重复");
                return response;
            }
        }

        long id = IDgenerator.nextId();
        Dict entity = MapperUtil.map(request, Dict.class);
        entity.setId(id);

        long result = dictMapper.insert(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.CREATE_FAILURE);
            return response;
        }
        response.setId(id);

        return response;
    }

    /**
     * 逻辑删除
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public DictDeleteResponse delete(DictDeleteRequest request, Token token) {
        DictDeleteResponse response = new DictDeleteResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = dictMapper.delete(request.getId(), token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.DELETE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 更新
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public DictUpdateResponse update(DictUpdateRequest request, Token token) {
        DictUpdateResponse response = new DictUpdateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        Dict entity = dictMapper.getById(request.getId(), token);
        if (entity == null) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
            return response;
        }

        MapperUtil.map(request, entity);
        long result = dictMapper.update(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 查询
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public DictFindResponse find(DictFindRequest request, Token token) {
        DictFindResponse response = new DictFindResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getPageSize() != 0) {
            PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        }
        if (StringUtil.isNotEmpty(request.getSortKey())) {
            PageHelper.orderBy(request.getSortKey() + " " + request.getSortType());
        }
        PageInfo<Dict> pageInfo = new PageInfo<>(dictMapper.find(request, token));

        response.setResult(pageInfo.getList());
        response.setTotalCount(pageInfo.getTotal());

        return response;
    }

    @Override
    public DictLoadResponse load(DictLoadRequest request, Token token) {
        DictLoadResponse response = new DictLoadResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        DictFindRequest dictFindRequest = new DictFindRequest();
        dictFindRequest.setDictName(request.getDictName());
        dictFindRequest.setValid(true);
        List<Dict> dicts = dictMapper.find(dictFindRequest, token);
        if (dicts.size() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "[" + request.getDictName() + "]字典不存在");
            return response;
        } else if (dicts.size() > 1) {
            response.addError(ErrorType.BUSINESS_ERROR, "字典重复异常，请联系管理员");
            return response;
        }
        response.setDict(dicts.get(0));

        DictItemFindRequest dictItemFindRequest = new DictItemFindRequest();
        dictItemFindRequest.setDictName(request.getDictName());
        dictItemFindRequest.setValid(true);
        dictItemFindRequest.setPageSize(0);
        DictItemFindResponse dictItemFindResponse = dictItemManager.find(dictItemFindRequest, token);
        if (dictItemFindResponse.hasError()) {
            response.addErrors(dictItemFindResponse.getErrors());
            return response;
        }
        response.setDictItems(dictItemFindResponse.getResult());
        return response;
    }
}
